package cn.kone.listener;

import cn.kone.pojo.domain.Order;
import cn.kone.pojo.dto.OrderPayDTO;
import cn.kone.service.IOrderService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * RocketMQ事务监听器
 */
@Component
@RocketMQTransactionListener
public class TransactionListener implements RocketMQLocalTransactionListener {

    @Autowired
    private IOrderService orderService;

    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {
        try {
            Order order = (Order)arg;
            //将订单状态改为未付款
            order.setStatus(6);
            order.setUpdateTime(new Date()); //新增修改时间
            orderService.updateById(order); //修改订单持久化到mysql
            return RocketMQLocalTransactionState.COMMIT; //提交事务
        } catch (Exception e) {
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;//回滚事务
        }

    }


    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
        String json = new String((byte[]) msg.getPayload(), StandardCharsets.UTF_8);
        OrderPayDTO orderPayDTO = JSON.parseObject(json, OrderPayDTO.class);

        Order order = orderService.getOne(new LambdaQueryWrapper<Order>().eq(Order::getOrderNo, orderPayDTO.getOrderNo()));

        if (6!=order.getStatus()){
            return RocketMQLocalTransactionState.COMMIT;
        }

        return RocketMQLocalTransactionState.ROLLBACK;//回滚事务
    }
}
